import axios from "axios";
import { useCounterStore } from '@/stores/counter'
import { ElMessage } from "element-plus";

const read = axios.create({
    baseURL: "/systemmanagereadapi",
    timeout: 5000,
})
//拦截器-读-请求
read.interceptors.request.use(
    config => {
        const counts = useCounterStore();
        config.headers.Authorization = "Bearer " + counts.Logins.token;
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
//拦截器-读-响应
read.interceptors.response.use(
    res => {
        return res
    },
    error => {
        if (error.status == 401) {
            ElMessage.error("令牌过期，请重新登录");
            setTimeout(() => {
                location.href = '/'
            }, 1000)
        }

        return Promise.reject(error)
    }
)

export { read }

// 写实例（POST/PUT/DELETE 等写接口统一走网关）
const write = axios.create({
    baseURL: "/systemmanagewriteapi",
    timeout: 5000,
})

// 拦截器-写-请求
write.interceptors.request.use(
    config => {
        const counts = useCounterStore();
        config.headers.Authorization = "Bearer " + counts.Logins.token;
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 拦截器-写-响应
write.interceptors.response.use(
    res => {
        return res
    },
    error => {
        if (error.response?.status === 401) {
            ElMessage.error("令牌过期，请重新登录");
            setTimeout(() => {
                location.href = '/'
            }, 1000)
        }
        return Promise.reject(error)
    }
)

// 菜单管理API封装
export const menuApi = {
    // 添加菜单
    async addMenu(menuData: any) {
        try {
            // 根据 MenusAdd.vue 中的原始请求，接口是 POST /api/SystemManagement/MenusAdd
            const response = await write.post('/api/SystemManagement/MenusAdd', menuData, {
                validateStatus: () => true // 允许所有状态码，我们自己处理
            })
            console.log('添加菜单响应:', response.status, response.data)

            // 处理成功情况（2xx状态码或特定的业务成功码）
            if (response.status >= 200 && response.status < 300) {
                ElMessage.success('菜单添加成功')
                return response.data
            } else {
                ElMessage.error(response.data?.message || '添加失败')
                throw new Error(response.data?.message || '添加失败')
            }
        } catch (error) {
            console.error('添加菜单失败:', error)
            ElMessage.error('添加菜单失败')
            throw error
        }
    },

    // 更新菜单
    async updateMenu(id: number, menuData: any) {
        try {
            const response = await write.put(`/api/Menu/Update/${id}`, menuData)
            if (response.data.code === 200 || response.data.code === 400) {
                ElMessage.success('菜单更新成功')
                return response.data
            } else {
                ElMessage.error(response.data.message || '更新失败')
                throw new Error(response.data.message || '更新失败')
            }
        } catch (error) {
            console.error('更新菜单失败:', error)
            ElMessage.error('更新菜单失败')
            throw error
        }
    },

    // 删除菜单
    async deleteMenu(id: number) {
        try {
            // 根据之前的错误信息，后端接口是 POST /api/SystemManagement/MenusDel?id=xx
            const response = await write.post('/api/SystemManagement/MenusDel', null, {
                params: { id },
                validateStatus: () => true // 允许所有状态码，我们自己处理
            })
            console.log('删除菜单响应:', response.status, response.data)

            // 根据之前的逻辑，后端可能用 code: 500 表示成功
            if ((response.status >= 200 && response.status < 300) || (response.data && response.data.code === 500)) {
                ElMessage.success('菜单删除成功')
                return response.data
            } else {
                ElMessage.error(response.data?.message || '删除失败')
                throw new Error(response.data?.message || '删除失败')
            }
        } catch (error) {
            console.error('删除菜单失败:', error)
            ElMessage.error('删除菜单失败')
            throw error
        }
    },

    // 批量删除菜单
    async batchDeleteMenus(ids: number[]) {
        try {
            const response = await write.delete('/api/Menu/BatchDelete', { data: { ids } })
            if (response.data.code === 200 || response.data.code === 400) {
                ElMessage.success(`成功删除 ${ids.length} 个菜单`)
                return response.data
            } else {
                ElMessage.error(response.data.message || '批量删除失败')
                throw new Error(response.data.message || '批量删除失败')
            }
        } catch (error) {
            console.error('批量删除菜单失败:', error)
            ElMessage.error('批量删除菜单失败')
            throw error
        }
    }
}

export { write }